package com.sinosoft.flow.intercepter;

import com.auth0.jwt.interfaces.Claim;
import com.sinosoft.flow.token.generator.TokenByHS265;
import org.apache.http.auth.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: tangyongbo
 * @Description:
 * @Date: create in 2021/11/5 10:43
 */
@Component
public class TokenIntercepter implements HandlerInterceptor {

    @Autowired
    private TokenByHS265 tokenByHS265;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("Authorization");
        String s1= "";
        String s2= "";
        if(null==token){
         //   throw new AuthenticationException("token不正确");
            s1="admin";
            s2="1";
            System.out.println("非正常请求");
        }else{
            Map<String, Claim> stringClaimMap = tokenByHS265.verifyToken(token);
            s1=stringClaimMap.get("aud").asString();
            s2=stringClaimMap.get("userId").asString();
            System.out.println(s1+"-----------"+s2);
        }
        //验证token
        if("admin".equals(s1) && "1".equals(s2)){
            return true;
        }
        throw new AuthenticationException("token不正确");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
